package com.alipay.sofa.award.biz.service.impl;

import com.alipay.common.event.UniformEvent;
import com.alipay.common.event.UniformEventBuilder;
import com.alipay.common.event.UniformEventPublisher;
import com.alipay.common.event.impl.DefaultUniformEventBuilder;
import com.alipay.sofa.award.biz.service.facade.MqPublishRecordFacade;
import com.alipay.sofa.award.record.common.dal.dataobject.AwardRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * MqPublishRecordImpl
 *
 * @author yangguanchao
 * @since 2018/09/03
 */
public class MqPublishRecordImpl implements MqPublishRecordFacade {

    private static final Logger   logger              = LoggerFactory
                                                          .getLogger(MqPublishRecordImpl.class);

    private final static String   TOPIC               = "TP_DEFAULT";

    private final static String   EVENTCODE           = "EC_DEFAULT";

    private UniformEventPublisher mqPublisher;

    private UniformEventBuilder   uniformEventBuilder = new DefaultUniformEventBuilder();

    @Override
    public boolean publishAwardRecord(AwardRecord awardRecord) {
        if (logger.isInfoEnabled()) {
            logger.info("Publish a message.");
        }

        /* Create a message instance. */
        final UniformEvent message = uniformEventBuilder.buildUniformEvent(TOPIC, EVENTCODE);

        /* Set the business object as an event payload. */
        message.setEventPayload(awardRecord);
        /* Mark that a runtime exception must be thrown when publishing failure. */
        message.setThrowExceptionOnFailed(true);

        boolean publishSuccess = false;

        try {
            /* Do publish action. */
            mqPublisher.publishUniformEvent(message);
            publishSuccess = true;
            logger.info(
                "Public a message, success. TOPIC [{}] EVENTCODE [{}] id [{}] payload [{}]",
                new Object[] { message.getTopic(), message.getEventCode(), message.getId(),
                        message.getEventPayload() });
        } catch (Exception e) {
            logger.error("Public a message, failure. TOPIC [{}] EVENTCODE [{}] error [{}]",
                new Object[] { message.getTopic(), message.getEventCode(), e.getMessage() }, e);
        }

        return publishSuccess;
    }

    public void setMqPublisher(UniformEventPublisher mqPublisher) {
        this.mqPublisher = mqPublisher;
    }
}
